package com.lin.eat.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.util.Date;

public class JwtUtil {

    //定义生成签名的算法
    public static final SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
    //定义生成签名的密钥
    public static final String key = "12345678";
    //定义token存活时间
    public static final Long expireMills = 3600000L;

    public static String createToken(final String id,final String phone){

        Date now = DateTime.now().toDate();

        JwtBuilder builder = Jwts.builder()
                //用户id
                .setId(id)
                //主题
                .setSubject(phone)
                //签发者
                .setIssuer("Lnchy")
                //签发时间
                .setIssuedAt(now)
                //加密算法，密钥
                .signWith(algorithm,key);
        if(expireMills >= 0){
            Long realExpire = System.currentTimeMillis() + expireMills;
            builder.setExpiration(new Date(realExpire));
        }
        //生成 access token
        return builder.compact();
    }

    public static Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }

    public static boolean isExpiration(String token, String base64Security) {
        return parseJwt(token).getExpiration().before(new Date());
    }

}
